package com.airforce.service;

import com.airforce.model.index_award;
import com.airforce.utils.JsonUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DrawLotteryUtil {

    public static int drawGift(List<index_award> giftList){

        if(null != giftList && giftList.size()>0){
            List<Double> orgProbList = new ArrayList<Double>(giftList.size());
            for(index_award gift:giftList){
                //按顺序将概率添加到集合中
                orgProbList.add(gift.getPower());
            }

            return draw(orgProbList);

        }
        return -1;
    }

    public static int draw(List<Double> giftProbList){

        List<Double> sortRateList = new ArrayList<Double>();

        // 计算概率总和
        Double sumRate = 0D;
        for(Double prob : giftProbList){
            sumRate += prob;
        }

        if(sumRate != 0){
            double rate = 0D;   //概率所占比例
            for(Double prob : giftProbList){
                rate += prob;   
                // 构建一个比例区段组成的集合(避免概率和不为1)
                sortRateList.add(rate / sumRate);
            }

            // 随机生成一个随机数，并排序
            double random = Math.random();
            sortRateList.add(random);
            Collections.sort(sortRateList);

            // 返回该随机数在比例集合中的索引
            return sortRateList.indexOf(random);
        }


        return -1;
    }

    public static void main(String[] args) {
        index_award iphone = new index_award();
        iphone.setId(101);
        iphone.setAwardname("苹果手机");
        iphone.setPower(0.1D);

        index_award thanks = new index_award();
        thanks.setId(102);
        thanks.setAwardname("再接再厉");
        thanks.setPower(0.5D);

        index_award vip = new index_award();
        vip.setId(103);
        vip.setAwardname("优酷会员");
        vip.setPower(0.4D);

        index_award kong=new index_award();
        kong.setId(104);
        kong.setAwardname("什么都没有");
        kong.setPower(0.0D);

        List<index_award> list = new ArrayList<index_award>();
        list.add(vip);
        list.add(thanks);
        list.add(iphone);

        for(int i=0;i<100;i++){
            int index = drawGift(list);

            System.out.println(JsonUtil.toJson(list.get(index)));
        }
    }

}